//
//  ShoppingViewController.m
//  EastMarket
//
//  Created by 李鹏程 on 16/10/12.
//  Copyright © 2016年 guoguo. All rights reserved.
//

#import "ShoppingViewController.h"

static NSString *HttpBaseURL = @"http://m.donglin.me/api";

@interface ShoppingViewController ()
{
    UIView *viewBottom;
    UIView *viewShopping;
    UILabel *lblSettlementValue;
    NSInteger productNum;
    UITabBarItem * item;
    UIButton *btnSettlement;
    UIButton *allSelectBtn;
    UILabel *lblNoDataShow;
    UIView *viewNoDataShow;
}
@property (strong, nonatomic) NSMutableArray<CALayer *> *redLayers;

@end

@implementation ShoppingViewController

- (NSMutableArray<CALayer *> *)redLayers {
    if (!_redLayers) {
        _redLayers = [NSMutableArray array];
    }
    return _redLayers;
}

- (void)viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];
    [self loadViewCartProducts];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"购物车";
    globalManager.isAllProduct = YES;
    _sellerNameArr = [[NSMutableArray alloc] init];
    _itemListArr = [[NSMutableArray alloc] init];
    _cartItemGroupListArr = [[NSMutableArray alloc] init];
    _selectedItemListArr = [[NSMutableArray alloc] init];
    
    _itemCheckArr = [[NSMutableArray alloc] init];
    _itemUnCheckArr = [[NSMutableArray alloc] init];
    _itemIdListArr = [[NSMutableArray alloc] init];
    _numListArr = [[NSMutableArray alloc] init];
    item = [self.tabBarController.tabBar.items objectAtIndex:3];
    [self initShoppingCartListUI];
    [SVProgressHUD showWithStatus:@"加载中"];
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleCustom];
    [SVProgressHUD setForegroundColor:EastMarket_MainToneColor];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
    
    [self updateUIWithDateIsNull];
}

- (void)updateUIWithDateIsNull {

    CGFloat spacing = 8.0f;
    viewNoDataShow = [[UIView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH / 4, SCREEN_WIDTH / 4, SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)];
    viewNoDataShow.backgroundColor = [UIColor clearColor];
    [self.view addSubview:viewNoDataShow];
    
    UIImageView *imgEmoji = [[UIImageView alloc] initWithFrame:CGRectMake(viewNoDataShow.frame.size.width / 4, 8, viewNoDataShow.frame.size.width / 2, viewNoDataShow.frame.size.width / 2)];
    imgEmoji.image = [UIImage imageNamed:@"emoji"];
    [viewNoDataShow addSubview:imgEmoji];
    
    lblNoDataShow = [[UILabel alloc] initWithFrame:CGRectMake(0, imgEmoji.frame.origin.y + imgEmoji.frame.size.height + 2 * spacing, viewNoDataShow.frame.size.width, imgEmoji.frame.size.height / 2)];
    //    lblNoDataShow.backgroundColor = Baoejie_MainToneColor;
    lblNoDataShow.text = @"购物车现在是空的";
    lblNoDataShow.textAlignment = NSTextAlignmentCenter;
    lblNoDataShow.textColor = [UIColor darkGrayColor];
    lblNoDataShow.font = [UIFont boldSystemFontOfSize:16];
    [viewNoDataShow addSubview:lblNoDataShow];
    
    UIButton *btnNodataShow = [[UIButton alloc] initWithFrame:CGRectMake(0, lblNoDataShow.frame.origin.y + lblNoDataShow.frame.size.height + spacing, viewNoDataShow.frame.size.width, lblNoDataShow.frame.size.height)];
    [btnNodataShow setTitle:@"现在去购买" forState:UIControlStateNormal];
    [btnNodataShow setTitleColor:EastMarket_BlueColor forState:UIControlStateNormal];
    [btnNodataShow addTarget:self action:@selector(btnNodataShowClicked:) forControlEvents:UIControlEventTouchUpInside];
    [viewNoDataShow addSubview:btnNodataShow];
    
    viewNoDataShow.hidden = YES;
//    [self.view addSubview:lblNoDataShow];

}

- (void)btnNodataShowClicked:(UIButton *)sender {

    self.tabBarController.selectedIndex = 1;
}

- (void)initShoppingCartListUI {
    
    CGFloat border = 1.0f;
    CGFloat spacing = 8.0f;
    _tabView = [[UITableView alloc] initWithFrame:CGRectMake(0, -20, SCREEN_WIDTH, SCREEN_HEIGHT - TabBarHeight - TopBarHeight - 44 + 20) style:UITableViewStyleGrouped];
    _tabView.showsVerticalScrollIndicator = false;
    _tabView.delegate = self;
    _tabView.dataSource = self;
//    _tabView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tabView.editing = YES;
    _tabView.allowsMultipleSelectionDuringEditing = YES;
    _tabView.backgroundColor = EastMarket_backgroundColor;
   
    [self setExtraCellLineHidden:_tabView];
    [self.view addSubview:_tabView];
    
    viewBottom = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - TopBarHeight - TabBarHeight, SCREEN_WIDTH, TabBarHeight)];
    viewBottom.backgroundColor = [UIColor clearColor];
    [self.view addSubview:viewBottom];
    [self.view bringSubviewToFront:viewBottom];
    
    viewShopping = [[UIView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH * 3 / 5, SCREEN_HEIGHT - TopBarHeight - TabBarHeight, SCREEN_WIDTH / 5, TabBarHeight)];
    viewShopping.backgroundColor = [UIColor clearColor];
    [self.view addSubview:viewShopping];
    
    
    UIView *viewSettlement = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - TopBarHeight - TabBarHeight - 44, SCREEN_WIDTH, 44)];
    viewSettlement.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:viewSettlement];

    allSelectBtn = [[UIButton alloc] initWithFrame:CGRectMake(spacing + 2, (viewSettlement.frame.size.height - 25) / 2, 25, 25)];
//    if ([[[_allDataDict objectForKey:@"data"] objectForKey:@"checked"] integerValue] == 1) {
//        
//        [allSelectBtn setBackgroundImage:[UIImage imageNamed:@"checked"] forState:UIControlStateNormal];
//    } else if([[[_allDataDict objectForKey:@"data"] objectForKey:@"checked"] integerValue] == 0){
//    
//        [allSelectBtn setBackgroundImage:[UIImage imageNamed:@"unchecked"] forState:UIControlStateNormal];
//    }
    
    [allSelectBtn addTarget:self action:@selector(selecteAllCells:) forControlEvents:UIControlEventTouchUpInside];
    [viewSettlement addSubview:allSelectBtn];
    
    lblSettlementValue = [[UILabel alloc] initWithFrame:CGRectMake(allSelectBtn.frame.origin.x + allSelectBtn.frame.size.width + 10, 2, (viewSettlement.frame.size.width - allSelectBtn.frame.origin.x - allSelectBtn.frame.size.width - 10 - 1) * 3 / 4, viewSettlement.frame.size.height - 2 * 2)];
//    lblSettlementValue.textColor = EastMarket_MainToneColor;
    lblSettlementValue.backgroundColor = [UIColor clearColor];
    lblSettlementValue.font = [UIFont systemFontOfSize:20.0f];
    [viewSettlement addSubview:lblSettlementValue];
    
    btnSettlement = [[UIButton alloc] initWithFrame:CGRectMake(lblSettlementValue.frame.origin.x + lblSettlementValue.frame.size.width + border, 0, (viewSettlement.frame.size.width - allSelectBtn.frame.origin.x - allSelectBtn.frame.size.width - 10 - 1) / 4, viewSettlement.frame.size.height)];
    [btnSettlement addTarget:self action:@selector(btnSettlementClicked:) forControlEvents:UIControlEventTouchUpInside];
    btnSettlement.backgroundColor = EastMarket_MainToneColor;
    [viewSettlement addSubview:btnSettlement];
}

- (void)loadViewCartProducts {
    
    [NSThread detachNewThreadSelector:@selector(callServerGetCartProducts) toTarget:self  withObject:Nil];
}

- (void)callServerGetCartProducts {
    
    NSDictionary *dicOfCartProducts = [AppServiceInterface getCartProducts];
    [self performSelectorOnMainThread:@selector(updateCartProducts:) withObject:dicOfCartProducts waitUntilDone:NO];
}

- (void)updateCartProducts:(NSDictionary *)dic {
    [SVProgressHUD dismiss];
    _allDataDict = dic;
    if (dic && [[dic objectForKey:@"success"] integerValue] == 1) {
        if ([[dic objectForKey:@"code"] isEqualToString:@"LoginRequire"]) {
            LoginViewController *loginVC = [[LoginViewController alloc] init];
            [self.navigationController pushViewController:loginVC animated:true];
            return;
        }
        [_itemIdListArr removeAllObjects];
        [_numListArr removeAllObjects];
        if (_cartItemGroupListArr.count > 0) {
            [_cartItemGroupListArr removeAllObjects];
        }
        [_cartItemGroupListArr addObjectsFromArray:[[dic objectForKey:@"data"] objectForKey:@"cartItemGroupList"]];
        item.badgeValue = [NSString stringWithFormat:@"%@", [[dic objectForKey:@"data"] objectForKey:@"cartItemNum"]];
        
        [self updateSettlementValue:[NSString stringWithFormat:@"%@",[[dic objectForKey:@"data"] objectForKey:@"totalAmount"]]];
        [self updateSettlementBtnText:[NSString stringWithFormat:@"%@",[[dic objectForKey:@"data"] objectForKey:@"totalNum"]]];
        [_tabView reloadData];
        if (_cartItemGroupListArr.count < 1) {
            viewNoDataShow.hidden = NO;
        } else {
            viewNoDataShow.hidden = YES;
        }
    } else if(dic && [[dic objectForKey:@"success"] integerValue] != 1) {
        
        [GlobalUnit showAlertHint:@"温馨提示！" message:[NSString stringWithFormat:@"%@", [dic objectForKey:@"msg"]]];
    } else {
        
        [GlobalUnit showAlertHint:@"温馨提示！" message:@"请求服务器失败，请稍后重试"];
    }
}

- (void)callServerCartCheck:(NSArray *)productIDs {

    NSString *itemIdListStr = [productIDs componentsJoinedByString:@","];
    [_itemCheckArr removeAllObjects];
    NSDictionary *cartDic = [AppServiceInterface CartItemCheck:itemIdListStr];
    [self performSelectorOnMainThread:@selector(updateCartProductsAfterSelect:) withObject:cartDic waitUntilDone:NO];
}

- (void)updateCartProductsAfterSelect:(NSDictionary *)dic {

    if (dic && [[dic objectForKey:@"success"] integerValue] == 1) {
        [NSThread detachNewThreadSelector:@selector(callServerGetCartProducts) toTarget:self  withObject:Nil];
    }
}

- (void)callServerCartUnCheck:(NSArray *)productIDs {
    
    NSString *itemIdListStr = [productIDs componentsJoinedByString:@","];
    [_itemUnCheckArr removeAllObjects];
    NSDictionary *cartDic = [AppServiceInterface CartItemUnCheck:itemIdListStr];
    [self performSelectorOnMainThread:@selector(updateCartProductsAfterSelect:) withObject:cartDic waitUntilDone:NO];
}


// 结算
- (void)callServerOrderCreatePage {

    /*
    NSData* jsonDataWithItemIdList =[NSJSONSerialization dataWithJSONObject:_itemIdListArr
                                                      options:NSJSONWritingPrettyPrinted error:nil];
    NSString *itemIdListStr = [[NSString alloc] initWithData:jsonDataWithItemIdList
                                           encoding:NSUTF8StringEncoding];
    
    NSData* jsonDataWithNum =[NSJSONSerialization dataWithJSONObject:_itemIdListArr
                                                      options:NSJSONWritingPrettyPrinted error:nil];
    NSString *numListStr = [[NSString alloc] initWithData:jsonDataWithNum
                                                    encoding:NSUTF8StringEncoding];
     */
    
    
    //把数组转换成字符串
    NSString *itemIdListStr = [_itemIdListArr componentsJoinedByString:@","];
    NSString *numListStr = [_numListArr componentsJoinedByString:@","];
    
    NSDictionary *resultOfOrderCreatePage = [AppServiceInterface OrderCreatePage:itemIdListStr numList:numListStr];
    
    [self performSelectorOnMainThread:@selector(updateUIAfterOrderCreatePage:) withObject:resultOfOrderCreatePage waitUntilDone:NO];
}

- (void)updateUIAfterOrderCreatePage:(NSDictionary *)dic {

    [SVProgressHUD dismiss];
    debugMethod();
    if (dic && [[dic objectForKey:@"success"] integerValue] == 1) {
        FillInTheOrderViewController *fillInOrderVC = [[FillInTheOrderViewController alloc] init];
        fillInOrderVC.checkResultDic = [[dic objectForKey:@"data"] objectForKey:@"checkResult"];
        [fillInOrderVC setHidesBottomBarWhenPushed:true];
        [self.navigationController pushViewController:fillInOrderVC animated:true];
    } else if (dic && [[dic objectForKey:@"success"] integerValue] == 0) {
    
        [GlobalUnit showAlertHint:@"温馨提示！" message:[NSString stringWithFormat:@"%@", [dic objectForKey:@"msg"]]];
    } else {
    
        [GlobalUnit showAlertHint:@"温馨提示！" message:@"请求服务器失败，请稍后重试"];
    }
}


// 添加商品到购物车
- (void)loadViewCartItem:(NSString *)productID productNum:(NSInteger)productNums {
    
    _strProductID = productID;
    _productNumber = productNums;
    [NSThread detachNewThreadSelector:@selector(callServerGetPCartItem) toTarget:self  withObject:Nil];
}

- (void)callServerGetPCartItem {
    
    NSDictionary *dict = [AppServiceInterface cartItem:_strProductID itemNum:_productNumber];
    [self performSelectorOnMainThread:@selector(updateCartItem:) withObject:dict waitUntilDone:NO];
}

- (void)updateCartItem:(NSDictionary *)dic {
    
    if (dic && [[dic objectForKey:@"success"] integerValue] == 1) {
        if (![[dic objectForKey:@"data"] isKindOfClass:[NSNull class]]) {
            [NSThread detachNewThreadSelector:@selector(callServerGetCartProducts) toTarget:self  withObject:Nil];
        }
    }
}

#pragma mark -- UITableViewDelegate &  UITableViewDatasource

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 104;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return _cartItemGroupListArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    NSDictionary *itemListDic = _cartItemGroupListArr[section];
    NSArray * itemListDicArr = itemListDic[@"itemList"];
    return itemListDicArr.count;
}

- (void)updateSettlementValue:(NSString *)price {

    lblSettlementValue.text = [NSString stringWithFormat:@"合计:  %.2lf元", price.floatValue];
//    NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:lblSettlementValue.text];
//    
//    [attributeString setAttributes:@{NSForegroundColorAttributeName : EastMarket_MainToneColor,   NSFontAttributeName : [UIFont systemFontOfSize:20]} range:NSMakeRange(0, 2)];
//    
//    lblSettlementValue.attributedText = attributeString;
}

- (void)updateSettlementBtnText:(NSString *)text {

    if ([text isEqualToString:@"0"]) {
        btnSettlement.backgroundColor = EastMarket_darkGreyFontColor;
        btnSettlement.enabled = NO;
    } else {
    
        btnSettlement.backgroundColor = EastMarket_MainToneColor;
        btnSettlement.enabled = YES;
    }
    [btnSettlement setTitle:[NSString stringWithFormat:@"去结算(%@)", text] forState:UIControlStateNormal];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *cellIdentifier = @"cell";
    ShoppingViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (cell == nil) {
        cell = [[ShoppingViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    cell.selectedBackgroundView = [[UIView alloc] init];
    cell.selectionStyle = UITableViewCellSelectionStyleGray;
    cell.backgroundColor = [UIColor whiteColor];
    cell.btnFavorite.hidden = YES;
    NSDictionary *sellerNameDict = _cartItemGroupListArr[indexPath.section];
    NSArray *itemListArr = sellerNameDict[@"itemList"];
    cell.lblProductName.text = [itemListArr[indexPath.row] objectForKey:@"itemName"];
    cell.lblProductPrice.text = [NSString stringWithFormat:@"%.2lf元", [[itemListArr[indexPath.row] objectForKey:@"price"] floatValue]];
    if (![[itemListArr[indexPath.row] objectForKey:@"originalPrice"] isKindOfClass:[NSNull class]]) {
        cell.lblOriginalPrice.text = [NSString stringWithFormat:@"%.2lf元", [[itemListArr[indexPath.row] objectForKey:@"originalPrice"] floatValue]];
        //中划线
        NSDictionary *attribtDic =@{NSStrikethroughStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle]};
        NSMutableAttributedString *attribtStr = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%.2lf元", [[itemListArr[indexPath.row] objectForKey:@"originalPrice"] floatValue]] attributes:attribtDic];
        cell.lblOriginalPrice.attributedText = attribtStr;
    }
    [cell.imgProductIcon sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@", [itemListArr[indexPath.row] objectForKey:@"itemPic"]]] placeholderImage:[UIImage imageNamed:@"NoProductImage"]];
    productNum = [[itemListArr[indexPath.row] objectForKey:@"cartNum"] integerValue];
     cell.lblProductNum.text = [NSString stringWithFormat:@"%ld", productNum];

    if ([[[_allDataDict objectForKey:@"data"] objectForKey:@"checked"] integerValue] == 1) {
        
        [allSelectBtn setBackgroundImage:[UIImage imageNamed:@"checked"] forState:UIControlStateNormal];
    } else if([[[_allDataDict objectForKey:@"data"] objectForKey:@"checked"] integerValue] == 0){
        
        [allSelectBtn setBackgroundImage:[UIImage imageNamed:@"unchecked"] forState:UIControlStateNormal];
    }
    

    cell.tintColor = EastMarket_MainToneColor;
    
    if ([[itemListArr[indexPath.row] objectForKey:@"checked"] integerValue] == 1) {
        
        [_tabView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
        
    } else{
        [_tabView deselectRowAtIndexPath:indexPath animated:YES];
    }
    
    if ([[itemListArr[indexPath.row] objectForKey:@"checked"] integerValue] == 1) {
        [_itemIdListArr addObject:[itemListArr[indexPath.row] objectForKey:@"itemId"]];
        [_numListArr addObject:[itemListArr[indexPath.row] objectForKey:@"cartNum"]];
    } else {
    
        [_itemIdListArr removeObject:[itemListArr[indexPath.row] objectForKey:@"itemId"]];
        [_numListArr removeObject:[itemListArr[indexPath.row] objectForKey:@"cartNum"]];
    }

    cell.block=^(CGPoint point)
    {
        CGPoint startPoint = [self.view convertPoint:point fromView:self.tabView];
        CGPoint endpoint=[self.view convertPoint:viewShopping.center fromView:viewBottom];
        [self initCHLayerFromPoint:startPoint toPoint:endpoint];
    };

    cell.btnFavoriteClick = ^() {
        debugMethod();
        debugLog(@"%ld", indexPath.row);
    };
    
    cell.btnNumReduceClick = ^() {
        debugMethod();
        debugLog(@"%ld", indexPath.row);
        if (cell.lblProductNum.text.integerValue == 1) {
            UIAlertController *alerController = [UIAlertController alertControllerWithTitle:@"" message:@"确定删除当前商品吗？" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                NSLog(@"点击了取消按钮");
                return ;
            }];
            UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [_tabView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
                [self loadViewCartItem:[NSString stringWithFormat:@"%@", [itemListArr[indexPath.row] objectForKey:@"itemId"]] productNum:-1];
            }];
            [alerController addAction:cancleAction];
            [alerController addAction:defaultAction];
            [self  presentViewController:alerController animated:YES completion:nil];
        } else {
            [_tabView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
            [self loadViewCartItem:[NSString stringWithFormat:@"%@", [itemListArr[indexPath.row] objectForKey:@"itemId"]] productNum:-1];
        }
    };

    cell.btnNumAddClick = ^() {
        
        debugMethod();
        debugLog(@"%ld", indexPath.row);
        [_tabView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
        [self loadViewCartItem:[NSString stringWithFormat:@"%@", [itemListArr[indexPath.row] objectForKey:@"itemId"]] productNum:1];
    };
   
    return cell;
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {

    NSDictionary *sellerNameDict = _cartItemGroupListArr[indexPath.section];
    NSArray *itemListArr = sellerNameDict[@"itemList"];
    [_itemUnCheckArr addObject:[itemListArr[indexPath.row] objectForKey:@"itemId"]];
    [NSThread detachNewThreadSelector:@selector(callServerCartUnCheck:) toTarget:self  withObject:_itemUnCheckArr];
    debugLog(@"%ld%ld", indexPath.section, indexPath.row);
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    NSDictionary *sellerNameDict = _cartItemGroupListArr[indexPath.section];
    NSArray *itemListArr = sellerNameDict[@"itemList"];
        [_itemCheckArr addObject:[itemListArr[indexPath.row] objectForKey:@"itemId"]];
    [NSThread detachNewThreadSelector:@selector(callServerCartCheck:) toTarget:self  withObject:_itemCheckArr];
    debugLog(@"%ld%ld", indexPath.section, indexPath.row);
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    NSDictionary *sellerNameDict = _cartItemGroupListArr[section];

    CGFloat spacing = 10.0f;
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 35)];
    view.backgroundColor = [UIColor whiteColor];
    UIButton *btnSelectGroup = [[UIButton alloc] initWithFrame:CGRectMake(spacing, 5, 25, 25)];
    btnSelectGroup.tag = section;
    [btnSelectGroup addTarget:self action:@selector(btnSelectGroupPressed:) forControlEvents:UIControlEventTouchUpInside];
    if ([[sellerNameDict objectForKey:@"checked"] integerValue] == 1) {
        [btnSelectGroup setBackgroundImage:[UIImage imageNamed:@"checked"] forState:UIControlStateNormal];
    } else {
    
        [btnSelectGroup setBackgroundImage:[UIImage imageNamed:@"unchecked"] forState:UIControlStateNormal];
    }
    [view addSubview:btnSelectGroup];
    
    UILabel *lblTitleHeader = [[UILabel alloc]initWithFrame:CGRectMake(btnSelectGroup.frame.origin.x + btnSelectGroup.frame.size.width + spacing, 5, view.frame.size.width - btnSelectGroup.frame.origin.x - btnSelectGroup.frame.size.width - 2 * spacing, 25)];
    lblTitleHeader.textColor = [UIColor blackColor];
    lblTitleHeader.font = [UIFont systemFontOfSize:16];
    lblTitleHeader.text = sellerNameDict[@"sellerName"];
    [view addSubview:lblTitleHeader];
    
    return view;
}

- (void)btnSelectGroupPressed:(UIButton *)sender {

    debugLog(@"%ld", sender.tag);
    NSDictionary *sellerNameDict = _cartItemGroupListArr[sender.tag];
    
    if ([[sellerNameDict objectForKey:@"checked"] integerValue] == 1) {
        
        NSArray *itemListArr = sellerNameDict[@"itemList"];
        for (NSDictionary *dic in itemListArr) {
            [_itemUnCheckArr addObject:[dic objectForKey:@"itemId"]];
        }
        [NSThread detachNewThreadSelector:@selector(callServerCartUnCheck:) toTarget:self  withObject:_itemUnCheckArr];
    } else {
    
        NSArray *itemListArr = sellerNameDict[@"itemList"];
        for (NSDictionary *dic in itemListArr) {
            [_itemCheckArr addObject:[dic objectForKey:@"itemId"]];
        }
        [NSThread detachNewThreadSelector:@selector(callServerCartCheck:) toTarget:self  withObject:_itemCheckArr];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 35.0f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {

    return 16.0f;
}
//多余的空行上不显示分割线
- (void)setExtraCellLineHidden: (UITableView *)tableView{
    UIView *view =[ [UIView alloc]init];
    view.backgroundColor = [UIColor clearColor];
    [tableView setTableFooterView:view];
    [tableView setTableHeaderView:view];
}

- (void)initCHLayerFromPoint:(CGPoint)startPoint toPoint:(CGPoint)endPoint {
    
    CALayer *chLayer = [[CALayer alloc] init];
    [self.redLayers addObject:chLayer];
    
    chLayer.frame = CGRectMake(startPoint.x, startPoint.y, 15, 15);
    chLayer.cornerRadius = CGRectGetWidth(chLayer.frame)/2.f;
    chLayer.backgroundColor = [UIColor redColor].CGColor;
    [self.view.layer addSublayer:chLayer];
    
    CAKeyframeAnimation *CHAnimation=[CAKeyframeAnimation animationWithKeyPath:@"position"];
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, startPoint.x, startPoint.y);
    CGPathAddQuadCurveToPoint(path, NULL, endPoint.x, startPoint.y, endPoint.x, endPoint.y);
    
    CHAnimation.path = path;
    CHAnimation.removedOnCompletion = NO;
    CHAnimation.fillMode = kCAFillModeBoth;
    CHAnimation.duration = 0.5;
    CHAnimation.delegate = self;
    [chLayer addAnimation:CHAnimation forKey:nil];
}

-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
    [self.redLayers[0] removeFromSuperlayer];
    [self.redLayers removeObjectAtIndex:0];
}

- (void)btnSettlementClicked:(UIButton *)btn {

    debugMethod();
    [SVProgressHUD showWithStatus:@"加载中"];
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleCustom];
    [SVProgressHUD setForegroundColor:EastMarket_MainToneColor];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];

    [NSThread detachNewThreadSelector:@selector(callServerOrderCreatePage) toTarget:self  withObject:Nil];
}

#pragma mark Actions
- (void)selecteAllCells:(UIButton *)sender {
    
    if (_allDataDict && [[_allDataDict objectForKey:@"success"] integerValue] == 1) {
        if ([[[_allDataDict objectForKey:@"data"] objectForKey:@"checked"] integerValue] == 0) {
//            [sender setTitle:@"取消" forState:UIControlStateNormal];
            [sender setBackgroundImage:[UIImage imageNamed:@"checked"] forState:UIControlStateNormal];
            for (NSDictionary *dicA in _cartItemGroupListArr) {
                for (NSDictionary *dicB in [dicA objectForKey:@"itemList"]) {
                    [_itemCheckArr addObject:[dicB objectForKey:@"itemId"]];
                }
            }
            
            [NSThread detachNewThreadSelector:@selector(callServerCartCheck:) toTarget:self  withObject:_itemCheckArr];
        } else {
//            [sender setTitle:@"全选" forState:UIControlStateNormal];
            [sender setBackgroundImage:[UIImage imageNamed:@"unchecked"] forState:UIControlStateNormal];
            for (NSDictionary *dicA in _cartItemGroupListArr) {
                for (NSDictionary *dicB in [dicA objectForKey:@"itemList"]) {
                    
                    [_itemUnCheckArr addObject:[dicB objectForKey:@"itemId"]];
                }
            }
            
            [NSThread detachNewThreadSelector:@selector(callServerCartUnCheck:) toTarget:self  withObject:_itemUnCheckArr];
        }
    } else {
    
        debugLog(@"服务器发生异常");
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
